

import { useEffect, useState } from "react";
import instance from "../../axios/index";
import './article.scss';
import ReactPaginate from "react-paginate";
import { message, Popconfirm, Button, Collapse } from 'antd';
import { Empty } from 'antd';
interface Item {
    title1: string;
    id: number;
    content1: string;
    time1: string;
    upvote: number;
    reading: number;
}

function Articlechearch() {
    const [shuju, setShuju] = useState<Item[]>([]);
    const [currentPage, setCurrentPage] = useState(0);
    const [postsPerPage] = useState(10); // 每页显示的文章数量，可根据需求调整
    const [isLoading, setIsLoading] = useState(true); // 添加数据加载状态
    const { Panel } = Collapse;
    // 用来渲染医生文章
    useEffect(() => {
        setIsLoading(true); // 设置为正在加载
        if (localStorage.getItem("guan") === "医生登录") {
            instance
                .post("/api/doctorarticle", {
                    identitycard: localStorage.getItem("identitycard"),
                })
                .then((res) => {
                    console.log(res.data.data, "医生");
                    setShuju(res.data.data);
                    setIsLoading(false); // 数据获取成功，设置为加载完成
                });
        } else if (localStorage.getItem("guan") === "管理员登录") {
            instance.post("/api/articlecha").then((res) => {
                console.log(res.data.data, "resss");
                setShuju(res.data.data);
                setIsLoading(false); // 数据获取成功，设置为加载完成
            });
        }
    }, [location]);

    // 计算当前页要显示的文章（需要确保shuju有值时再计算）
    const indexOfLastPost = (currentPage + 1) * postsPerPage;
    const indexOfFirstPost = indexOfLastPost - postsPerPage;
    const currentPosts = shuju && shuju.slice(indexOfFirstPost, indexOfLastPost) || [];

    // 处理分页点击事件
    // @ts-ignore
    const handlePageClick = (data) => {
        setCurrentPage(data.selected);
    };
    // 点击删除 
    // @ts-ignore
    const confirm = (id) => {
        instance.post('/api/doctordeletearticle', { id: id }).then((res) => {
            if (res.data.code === 200) {
                message.success('删除成功');
                if (localStorage.getItem("guan") === "医生登录") {
                    instance
                        .post("/api/doctorarticle", {
                            identitycard: localStorage.getItem("identitycard"),
                        })
                        .then((res) => {
                            console.log(res.data.data, "医生");
                            setShuju(res.data.data);
                        });
                } else if (localStorage.getItem("guan") === "管理员登录") {
                    instance.post("/api/articlecha").then((res) => {
                        console.log(res.data.data, "resss");
                        setShuju(res.data.data);
                    });
                }
            }
        })
    };

    const cancel = () => {
        message.error('取消删除');
    };
    return (
        <div className="box">
            {isLoading ? (
                <div>数据正在加载中，请稍候...</div>
            ) : shuju === undefined ? (
                <div>
                    <Empty/>
                </div>
            ) : (
                <>
                    <Collapse>
                        {currentPosts.map((item, index) => {
                            return (
                                <Panel header={<div className="panel-header">{item.title1}
                                    <Popconfirm
                                        title="确定要删除吗？亲！"
                                        onConfirm={() => confirm(item.id)}
                                        onCancel={cancel}
                                        okText="确定"
                                        cancelText="取消"
                                    >
                                        <Button danger>删除</Button>
                                    </Popconfirm>
                                </div>} key={index}>
                                    <div className="panel-content">
                                        <p className="title"> {item.title1}</p>
                                        <p className="content"> {item.content1}</p>
                                        <p className="time"> {item.time1} 点赞: {item.upvote} 阅读: {item.reading}</p>
                                    </div>
                                </Panel>
                            );
                        })}
                    </Collapse>
                    <ReactPaginate
                        previousLabel={"上一页"}
                        nextLabel={"下一页"}
                        breakLabel={""} // 隐藏省略号
                        pageCount={Math.ceil(shuju.length / postsPerPage)}
                        marginPagesDisplayed={2}
                        pageRangeDisplayed={5}
                        onPageChange={handlePageClick}
                        containerClassName={"pagination-wrapper"} // 外层容器样式类
                        subContainerClassName={"pagination"} // 分页按钮容器样式类
                        activeClassName={"active-page"} // 当前页按钮样式类
                        disabledClassName={"disabled-page"} // 禁用按钮样式类
                        pageClassName={"page-item"} // 单个页面按钮样式类
                        pageLinkClassName={"page-link"} // 页面按钮链接样式类
                        previousClassName={"previous-page"} // 上一页按钮样式类
                        nextClassName={"next-page"} // 下一页按钮样式类
                    />
                </>
            )}
        </div>
    );
}

export default Articlechearch;